import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import { findDOMNode } from 'react-dom';
import { DragSource, DropTarget } from 'react-dnd';

const style = {
	border: '1px dashed gray',
	padding: '0.5rem 1rem',
	marginBottom: '.5rem',
	backgroundColor: 'white',
  cursor: 'move',
}
const twoLevelSource = {
  beginDrag(props) {
    return {
      id: props.id,
      index: props.index
    }
  }
}
const twoLevelTarget = {
  hover(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;
    if (dragIndex === hoverIndex) {
			return;
    }
    const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
		const clientOffset = monitor.getClientOffset();
		const hoverClientY = clientOffset.y - hoverBoundingRect.top;
    if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
			return;
		}
		if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
			return;
    }
    const lastId = props.lastId;
    props.moveAction(dragIndex, hoverIndex, 'twoLevel', lastId);
    monitor.getItem().index = hoverIndex;
  }
}
@DragSource('twoLevel', twoLevelSource, (connect, monitor) => {
  return {
    isDragging: monitor.isDragging(),
    connectDragSource: connect.dragSource()
  }
})
@DropTarget('twoLevel', twoLevelTarget, (connect) => {
  return {
    connectDropTarget: connect.dropTarget()
  }
})
export default class TwoLevelItem extends Component {
  static propTypes = {
    connectDragSource: PropTypes.func.isRequired,
		connectDropTarget: PropTypes.func.isRequired,
		index: PropTypes.number.isRequired,
		isDragging: PropTypes.bool.isRequired,
		id: PropTypes.any.isRequired,
		name: PropTypes.string.isRequired,
    moveAction: PropTypes.func.isRequired,
    lastId: PropTypes.any.isRequired
  }
  render() {
    const { name, isDragging, connectDragSource, connectDropTarget } = this.props;
    const opacity = isDragging ? 0.5 : 1;
    return connectDragSource(
      connectDropTarget(<div style={{ ...style, opacity }}>{ name }</div>)
    )
  }
}
